package cc.yugu.yhdw.webserver.service.basic;

import cc.yugu.yhdw.common.domain.basic.TerminalCode;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.webserver.persistence.basic.TerminalCodeMapper;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * 设备注册信息业务
 *
 * @Date:Created in 2018/7/5 14:40
 * @Author:
 * @Modified By: zjn 2018/7/5 14:40
 */
@Service
public class TerminalCodeService {
    @Autowired
    TerminalCodeMapper terminalCodeMapper;
    /**
    * 根据设备唯一码（id）查询表bas_terminal_code
    *
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.basic.TerminalCode
    * @Author By: zjn 2018/7/5  14:40
    */
    public TerminalCode find(String id) {
        return terminalCodeMapper.find(id);
    }
    /**
    * 分页查询
    *
    * @Param: [search]
    * @Return: cc.yugu.yhdw.common.entity.pagination.Page
    * @Author By: zjn 2018/7/5  14:40
    */
    public Page findPage(TerminalCode search) {
        Page page = search.buildPage();
        page.setTotalItems(terminalCodeMapper.findPageCount(search));
        search.setBeginIndex(page.getOffset());
        page.setResult(terminalCodeMapper.findPageResult(search));
        return page;
    }
    /**
    * 插入
    *
    * @Param: [entity]
    * @Return: int
    * @Author By: zjn 2018/7/5  14:40
    */
    public int insert(TerminalCode entity) {
        return terminalCodeMapper.insert(entity);
    }
    /**
    * to 的设备编号给 from
    *
    * @Param: [from, to]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  14:41
    */
    public ExtResult swap(String from, String to) {
        // 根据设备号码查询 唯一码和设备号码
        TerminalCode a = terminalCodeMapper.findByCode(from);
        if(a == null) {
            return ExtResult.failResult("终端编号[" + from + "]不存在");
        }

        TerminalCode b = terminalCodeMapper.findByCode(to);
        if(b == null) {
            return ExtResult.failResult("终端编号[" + to + "]不存在");
        }
        // 设置a的设备编号 为b的设备编号
        self().swapCode(a, b);
        return ExtResult.successResult();
    }

    @Transactional(rollbackFor=Throwable.class)
    public void swapCode(TerminalCode a, TerminalCode b) {
        String temp = "@@@@@@";
        synchronized (this) {
            // 根据唯一码(参数1) 更新设备编号(2)
            terminalCodeMapper.update(a.getId(), temp);
            terminalCodeMapper.update(b.getId(), a.getCode());
            terminalCodeMapper.update(a.getId(), b.getCode());
        }
    }

    private TerminalCodeService self() {
        return (TerminalCodeService) AopContext.currentProxy();
    }
}
